package com.movie.mybatis.service.impl;

import com.movie.mybatis.mapper.UserMapper;
import com.movie.mybatis.pojo.User;
import com.movie.mybatis.service.LoginAndExit;
import com.movie.mybatis.utils.SqlSessionUtil;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;

public class LoginAndExitServlet extends HttpServlet implements LoginAndExit {

    public void CookieJudge(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取浏览器的cookie
        Cookie[] cookies = request.getCookies();

        String username = null;
        String password = null;

        if (cookies != null){
            for(Cookie cookie : cookies){
                String name = cookie.getName();
                if ("username".equals(name)){
                    //找到用户账号对应的数据
                    username = cookie.getValue();
                }else if("password".equals(name)){
                    //找到用户密码对应的数据
                    password = cookie.getValue();
                }
            }
        }
        //进行Cookie登录
        try (SqlSession sqlSession = SqlSessionUtil.openSession()) {
            if (username != null && password != null){

                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                User user = mapper.selectLoginByUser(username, password);
                //登录成功
                if (user != null){
                    //应该成功了就要获取session，session会超时销毁
                    HttpSession session = request.getSession();
                    //将登录成功的用户放入session域
                    session.setAttribute("user",user);
                    //跳转主页面
                    response.sendRedirect(request.getContextPath()+"/record/list");
                }else {
                    //跳转登录
                    response.sendRedirect(request.getContextPath()+"/index.jsp");
                }
            }else {
                //跳转登录
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }
        }

    }

    public boolean Login(HttpServletRequest request,String jump){
        boolean success = false;
        User user;
        //获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //查询判断
        try (SqlSession sqlSession = SqlSessionUtil.openSession()) {
            if (jump.equals("record")) {
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                user = mapper.selectLoginByUser(username, password);
            } else {
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                user = mapper.selectLoginByRoot(username, password);
            }
            sqlSession.close();
            //登录成功
            if (user != null) {
                //且此seesion表示当前用户已成功登录
                HttpSession session = request.getSession();
                //将此用户存入session域中，前端显示
                session.setAttribute("user", user);
                success = true;
            }
            return success;
        }

    }

    public void NoLoginJudgment(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        //将此用户存入session域中，前端显示
        User user = (User)session.getAttribute("user");
        String username = user.getUserName();
        String password = user.getUserPassword();
        //创建Cookie对象存储登录名与密码
        Cookie cookie1 = new Cookie("username",username);
        Cookie cookie2 = new Cookie("password",password);
        //设置Cookie的有效时长
        cookie1.setMaxAge(60 * 60 * 24 * 10);
        cookie2.setMaxAge(60 * 60 * 24 * 10);
        //设置Cookie的路径（只要访问该项目。浏览器就要携带这两个cookie）
        cookie1.setPath(request.getContextPath());
        cookie2.setPath(request.getContextPath());
        //响应cookie给浏览器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }

    public void Exit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取当前的session对象，销毁
        HttpSession session = request.getSession(false);
        if (session != null){
            //删除当前session域中的user对象
            session.removeAttribute("user");
            //销毁服务器端的session对象
            session.invalidate();
            //销毁cookie（退出系统将所有的cookie销毁）
            Cookie[] cookies = request.getCookies();
            if (cookies != null){
                for (Cookie cookie :cookies){
                    //设置cookie的有效期为0.代表删除该cookie
                    cookie.setMaxAge(0);
                    //设置cookie的路径与浏览器的一致
                    cookie.setPath(request.getContextPath());
                    //响应cookie给浏览器，浏览器会将之前的cookie覆盖，也就是删除
                    response.addCookie(cookie);
                }
            }
            //退出后返回到初始判断页面
            response.sendRedirect(request.getContextPath());
        }
    }

}
